package com.saifan.wyy_ov.ui.property;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.data.bean.PopBean;
import com.saifan.wyy_ov.data.bean.RequestBean;
import com.saifan.wyy_ov.data.bean.RoomInfoBean;
import com.saifan.wyy_ov.data.bean.ServiceBean;
import com.saifan.wyy_ov.data.bean.ServiceItemBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IListViewOnClick;
import com.saifan.wyy_ov.model.interfaces.IViewOnClick;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.DateTimePickUtils;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.PopUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lomasky.ma.xui.Spinner;

/**
 * @version V1.0.0
 * @author: lomasky
 * @date: 2015-05-07 20:18
 * @descrption 特约服务
 */
public class EngagedServiceActivity extends BaseActivity {
    private static final int SELECTED_CONTACTS = 1212;
    private Toolbar toolbar;
    private EditText contacts;



    private List<ServiceItemBean> serviceItemBeans;
    private EditText housnumber;

    private EditText time;
    private EditText tel;
    RoomInfoBean roomInfoBean;
    private EditText description;
    private View loadlay;
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, Contacts.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomInfoBean = getRoomInfoBean();
        setContentView(R.layout.activity_engaged_service_activity);
        this.spinner = (Spinner) findViewById(R.id.spinner);
        this.description = (EditText) findViewById(R.id.description);
        this.tel = (EditText) findViewById(R.id.tel);
        this.contacts = (EditText) findViewById(R.id.contacts);
        this.time = (EditText) findViewById(R.id.time);

        this.housnumber = (EditText) findViewById(R.id.housnumber);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (roomInfoBean != null) {
            housnumber.setText(roomInfoBean.getXMDA_XMMC() + "" + roomInfoBean.getWYFJDA_FJMC());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            time.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
            tel.setText(roomInfoBean.getWYKHDA_SJ() + "");
            contacts.setText(roomInfoBean.getWYKHDA_KHMC() + "");

        }
        queryServiceItem();


    }


    public void specialDate(View view) {
        DateTimePickUtils.show(this, new IViewOnClick() {
            @Override
            public void onClick(Object... object) {
                time.setText(object[0].toString());
            }
        }, new Date());
    }

    public void getContacts(View view) {

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS }, SELECTED_CONTACTS);
                return;
            }else {
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_CONTACTS);
            }
        }else {
            Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(i, SELECTED_CONTACTS);
        }

    }

    public void submit(View view) {
        if (getRoomInfoBean().getUserType() == 2) {
            for (PermissionsBean permissionsBean : getPermissions()) {
                if (permissionsBean.getYKQX_GNMC().equals("特约服务")) {
                    if (isEmpty(spinner)) {
                        ToastUtil.showToast(this, "请选择服务项目");
                        return;
                    }
                    if (isEmpty(description)) {
                        ToastUtil.showToast(this, "请输入内容");
                        description.setFocusable(true);
                        return;
                    }
                    GetData getData = new GetData();
                    ServiceBean serviceBean = new ServiceBean(time.getText().toString(), description.getText().toString(), roomInfoBean.getFKGX_ZJ(), contacts.getText().toString(), tel.getText().toString(), spinner.getText().toString(), roomInfoBean.getXMBS());
                    serviceBean.setTYFW_DZ(getRoomInfoBean().getWYFJDA_FJMC());
                    getData.getDataJson(this, Api.Customer.SPECIAL_SERVICE_SUBMIT, serviceBean, getString(R.string.wait), new ResponseData() {
                        @Override
                        public void onSuccess(String json) {
                            finish();

                        }

                        @Override
                        public void onFailed(String str) {


                        }
                    });
                    return;
                }
            }
            ToastUtil.showToast(EngagedServiceActivity.this, "您的权限不能进行此操作");
            return;
        } else if (getRoomInfoBean().getUserType() == 3) {
            ToastUtil.showToast(EngagedServiceActivity.this, "您的权限不能进行此操作");
            return;
        }

        if (isEmpty(spinner)) {
            ToastUtil.showToast(this, "请选择服务项目");
            if (!serverItems.isEmpty()) {
                spinner.popWindow.show();
            }
            return;
        }
        if (isEmpty(description)) {
            ToastUtil.showToast(this, "请输入内容");
            description.setFocusable(true);
            return;
        }
        GetData getData = new GetData();
        ServiceBean serviceBean = new ServiceBean(time.getText().toString(), description.getText().toString(), roomInfoBean.getFKGX_ZJ(), contacts.getText().toString(), tel.getText().toString(), spinner.getText().toString(), roomInfoBean.getXMBS());
        serviceBean.setTYFW_DZ(getRoomInfoBean().getWYFJDA_FJMC());
        getData.getDataJson(this, Api.Customer.SPECIAL_SERVICE_SUBMIT, serviceBean, getString(R.string.wait), new ResponseData() {
            @Override
            public void onSuccess(String json) {
                finish();

            }

            @Override
            public void onFailed(String str) {


            }
        });


    }

//    public void specialServiceType(View view) {
//        final int id = view.getId();
//        if (popupWindow == null) {
//            popupWindow = PopUtil.createPopupWindow(this, popBeans, new IListViewOnClick() {
//                @Override
//                public void onClick(int position) {
//                    ServiceItemBean serviceItemBean = serviceItemBeans.get(position);
//                    if (serviceItemBean != null) {
//                        if (!StringUtil.isNullOrEmpty(serviceItemBean.getTYFWXM_MC())) {
//                            serviceitem.setText(serviceItemBean.getTYFWXM_MC());
//                        }
//                    }
//
//                }
//            });
//            popupWindow.setWidth(view.getMeasuredWidth());
//        }
//
//
//        popupWindow.showAsDropDown(view);
//
//    }

    List<String> serverItems = new ArrayList<>();

    public void queryServiceItem() {

        GetData getData = new GetData();
        getData.getDataJson(this, Api.Customer.SPECIAL_SERVICE_TYPE, new RequestBean(getRoomInfoBean().getXMBS()), "", new ResponseData() {
            @Override
            public void onSuccess(String json) {

                serviceItemBeans = new Gson().fromJson(json, new TypeToken<List<ServiceItemBean>>() {
                }.getType());
                if (serviceItemBeans != null && !serviceItemBeans.isEmpty()) {
                    for (ServiceItemBean item : serviceItemBeans) {
                        serverItems.add(item.getTYFWXM_MC());


                    }
                    spinner.setList(serverItems);
                }


            }

            @Override
            public void onFailed(String str) {

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_repair, menu);
        return super.onCreateOptionsMenu(menu);
    }


    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.history_record) {
            Intent intent = new Intent();
            intent.setClass(this, EngagedServiceRecordActivity.class);
            startActivity(intent);

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case SELECTED_CONTACTS:
                if (!(resultCode == RESULT_OK)) {
                    return;
                }
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                String name = "";
                String number = "";

                try {
                    Cursor cursor = getContentResolver().query(uri, null, null, null,
                            null);
                    if (cursor != null && cursor.moveToFirst()) {

                        int contactId = Integer.valueOf(cursor.getString(cursor.getColumnIndex(Contacts._ID)));
                        name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                            if (phones.moveToFirst()) {
                                //遍历所有的电话号码
                                number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                            }
                        }
//
                        cursor.close();
                        tel.setText(number.replace(" ",""));
                        contacts.setText(name);

                    }
                } catch (Exception e) {
                    LogUtil.e(e.toString());
                }

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode==SELECTED_CONTACTS){

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(i, SELECTED_CONTACTS);


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用了读取通讯录权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

}